package com.seecen.controller;

import com.seecen.common.BaseResponse;
import com.seecen.common.ResultUtils;
import com.seecen.exception.ErrorCode;
import com.seecen.pojo.entity.ServiceEntity;
import com.seecen.pojo.entity.Category;
import com.seecen.service.ServiceService;
import com.seecen.service.CategoryService;
import com.seecen.utils.FileUploadUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: news
 * @description:
 * @author: ZGJ
 * @create: 2025-10-14 15:16
 * @version: 1.0
 **/
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileUploadUtil fileUploadUtil;

    @Resource
    private ServiceService serviceService;
    
    @Resource
    private CategoryService categoryService;
    @PostMapping("/admin/image")
    public BaseResponse<?> adminUploadImage(
            @RequestParam("image") MultipartFile file,
            @RequestParam(value = "servicename", required = false) String servicename,
            @RequestParam(value = "price", required = false) String price,
            @RequestParam(value = "description", required = false) String description,
            @RequestParam(value = "categoryid", required = false) String categoryid) {
        try {
            log.info("接收到图片上传请求，文件名：{}，大小：{} bytes",
                    file.getOriginalFilename(), file.getSize());
            log.info("服务参数 - 名称: {}, 价格: {}, 描述: {}, 分类: {}", 
                    servicename, price, description, categoryid);
            String imageUrl = fileUploadUtil.uploadImage(file);
            log.info("图片上传完成，URL: {}", imageUrl);
            Map<String, Object> result = new HashMap<>();
            result.put("url", imageUrl);
            result.put("name", file.getOriginalFilename());
            result.put("size", String.valueOf(file.getSize()));

            ServiceEntity serviceEntity = new ServiceEntity();
            
            // 设置服务名称，优先使用传入的参数，否则使用文件名
            String finalServiceName = (servicename != null && !servicename.trim().isEmpty()) 
                ? servicename 
                : file.getOriginalFilename().replace(".png", "").replace(".jpg", "").replace(".jpeg", "");
            serviceEntity.setServicename(finalServiceName);
            
            // 设置价格
            if (price != null && !price.trim().isEmpty()) {
                try {
                    serviceEntity.setPrice(new java.math.BigDecimal(price));
                } catch (NumberFormatException e) {
                    log.warn("价格格式错误，使用默认值0: {}", price);
                    serviceEntity.setPrice(new java.math.BigDecimal("0"));
                }
            } else {
                serviceEntity.setPrice(new java.math.BigDecimal("0"));
            }
            
            // 设置描述
            serviceEntity.setDescription(description != null ? description : "");
            
            // 设置分类ID
            if (categoryid != null && !categoryid.trim().isEmpty()) {
                try {
                    serviceEntity.setCategoryid(Long.parseLong(categoryid));
                } catch (NumberFormatException e) {
                    log.warn("分类ID格式错误，使用默认值1: {}", categoryid);
                    serviceEntity.setCategoryid(1L);
                }
            } else {
                serviceEntity.setCategoryid(1L);
            }
            
            serviceEntity.setCreatetime(new Date());
            serviceEntity.setUpdatetime(new Date());
            serviceEntity.setIsdeleted(0);
            serviceEntity.setServicepicture(imageUrl);

            // 存放图片到服务
            boolean success = serviceService.save(serviceEntity);
            if (!success) {
                log.error("保存服务失败");
                return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "保存服务失败");
            }

            // 将创建的服务信息添加到返回结果中
            result.put("service", serviceEntity);
            
            log.info("图片上传成功，服务创建成功，访问路径：{}", imageUrl);

            return ResultUtils.success(result);
        } catch (IOException e) {
            log.error("图片上传失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "图片上传失败: " + e.getMessage());
        }
    }

    @PostMapping("image")
    public BaseResponse<?> uploadImage(@RequestParam("image") MultipartFile file) {
        try {
            log.info("接收到图片上传请求，文件名：{}，大小：{} bytes",file.getOriginalFilename(),file.getSize());
            String imagUrl=fileUploadUtil.uploadImage(file);
            Map<String,String> result=new HashMap<>();
            result.put("url",imagUrl);
            result.put("name",file.getOriginalFilename());
            result.put("size",String.valueOf(file.getSize()));
            log.info("图片上传成功，访问路劲：{}",imagUrl);
            return ResultUtils.success(result);
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

    /**
     * 分类专用图片上传接口
     */
    @PostMapping("/admin/category/image")
    public BaseResponse<?> adminUploadCategoryImage(
            @RequestParam("image") MultipartFile file,
            @RequestParam(value = "categoryname", required = false) String categoryname,
            @RequestParam(value = "categorytype", required = false) String categorytype) {
        try {
            log.info("接收到分类图片上传请求，文件名：{}，大小：{} bytes",
                    file.getOriginalFilename(), file.getSize());
            log.info("分类参数 - 分类名称: {}, 分类类型: {}", categoryname, categorytype);
            
            String imageUrl = fileUploadUtil.uploadImage(file);
            log.info("分类图片上传完成，URL: {}", imageUrl);
            
            Map<String, Object> result = new HashMap<>();
            result.put("url", imageUrl);
            result.put("name", file.getOriginalFilename());
            result.put("size", String.valueOf(file.getSize()));

            // 如果有分类名称参数，则创建分类
            if (categoryname != null && !categoryname.trim().isEmpty()) {
                Category category = new Category();
                category.setCategoryname(categoryname);
                category.setCategoryimage(imageUrl);
                category.setCreatetime(new Date());
                category.setUpdatetime(new Date());
                
                // 设置分类类型，优先使用传入的参数，否则使用默认值1
                if (categorytype != null && !categorytype.trim().isEmpty()) {
                    try {
                        category.setCategorytype(Long.parseLong(categorytype));
                    } catch (NumberFormatException e) {
                        log.warn("分类类型格式错误，使用默认值1: {}", categorytype);
                        category.setCategorytype(1L);
                    }
                } else {
                    category.setCategorytype(1L);
                }
                
                boolean categorySuccess = categoryService.save(category);
                if (categorySuccess) {
                    result.put("category", category);
                    log.info("分类创建成功: {}, 类型: {}", categoryname, category.getCategorytype());
                } else {
                    log.warn("分类创建失败: {}", categoryname);
                }
            }
            
            log.info("分类图片上传成功，访问路径：{}", imageUrl);

            return ResultUtils.success(result);
        } catch (IOException e) {
            log.error("分类图片上传失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "分类图片上传失败: " + e.getMessage());
        }
    }
}
